<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>15-动态生成表格</title>
  <style>
    table {
      width: 500px;
      margin: 100px auto;
      border-collapse: collapse;
      text-align: center;
    }

    td,
    th {
      border: 1px solid #333;
    }

    thead tr {
      height: 40px;
      background-color: #ccc;
    }
  </style>
</head>

<body>
  <table cellspacing="0">
    <thead>
      <tr>
        <th>姓名</th>
        <th>科目</th>
        <th>成绩</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>

    </tbody>
  </table>
  <script>
    // 1. 准备需要生成的学生数据
    var datas = [
      {
        name: '魏璎珞',
        subject: 'JavaScript',
        score: 100
      },
      {
        name: '宏利',
        subject: 'JavaScript',
        score: 88
      },
      {
        name: '小陈',
        subject: 'JavaScript',
        score: 90
      },
      {
        name: '搜达',
        subject: 'JavaScript',
        score: 10
      },
      {
        name: '大猪蹄子',
        subject: 'JavaScript',
        score: 0
      }
    ];

    // 2. 节点生成
    // a. 行：对应人数，多少人创建几行
    var tbody = document.querySelector('tbody');
    for (var i = 0; i < datas.length; i++) {
      // 创建tr行
      var tr = document.createElement('tr');
      tbody.appendChild(tr);

      // 3. 行内创建单元格：单元格对应对象中的属性个数
      for (var j in datas[i]) {
        var td = document.createElement('td');
        td.innerHTML = datas[i][j];
        tr.appendChild(td);
      }
      var td = document.createElement('td');
      td.innerHTML = '<a href="javascript:;">删除</a>';
      tr.appendChild(td);
    }

    // 4. 删除元素
    var as = document.querySelectorAll('a');
    for (var i = 0; i < as.length; i++) {
      as[i].onclick = function () {
        tbody.removeChild(this.parentNode.parentNode);
      }
    }

  </script>
</body>

</html>